package accesslog

import (
	"encoding/json"
	"fmt"

	web "gitee.com/youkelike/web"
)

type MiddlewareBuilder struct {
	logFunc func(accesslog string)
}

func (b *MiddlewareBuilder) Logfunc(logfunc func(accesslog string)) *MiddlewareBuilder {
	b.logFunc = logfunc
	return b
}

func NewBuilder() *MiddlewareBuilder {
	return &MiddlewareBuilder{
		logFunc: func(accesslog string) {
			fmt.Println(accesslog)
		},
	}
}

type accesslog struct {
	Host       string
	Route      string
	HTTPMethod string
	Path       string
}

func (b *MiddlewareBuilder) Build() web.Middleware {
	return func(next web.HandlerFunc) web.HandlerFunc {
		return func(ctx *web.Context) {
			// 日志记录必须在解析完请求数据后执行
			defer func() {
				l := accesslog{
					Host:       ctx.Req.Host,
					Route:      ctx.MathedRoute,
					HTTPMethod: ctx.Req.Method,
					Path:       ctx.Req.URL.Path,
				}
				val, _ := json.Marshal(l)
				b.logFunc(string(val))
			}()

			next(ctx)
		}
	}
}
